package com.movies.service.controller.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.movies.service.common.Constants;
import com.movies.service.common.Result;
import com.movies.service.entity.Cinema;
import com.movies.service.service.CinemaService;
import com.movies.service.mapper.CinemaMapper;
// 新增：座位服务与实体
import com.movies.service.service.SeatService;
import com.movies.service.entity.Seat;
// 新增：JSON 解析
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/admin/cinema")
@SaCheckLogin
@SaCheckRole("ADMIN")
public class AdminCinemaController {

    @Autowired
    private CinemaService cinemaService; // 仅分页
    @Autowired
    private CinemaMapper cinemaMapper;   // 原生 SQL CRUD
    //
    @Autowired
    private SeatService seatService;

//    分页查询影院列表（支持按名称/状态筛选）
    @GetMapping("/page")
    public Result page(@RequestParam(defaultValue = "1") Integer pageNo,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) String cname,
                       @RequestParam(required = false) String status) {
        LambdaQueryWrapper<Cinema> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(cname != null && !cname.isEmpty(), Cinema::getCname, cname)
                .eq(status != null && !status.isEmpty(), Cinema::getStatus, status);
        Page<Cinema> page = cinemaService.page(new Page<>(pageNo, pageSize), wrapper);
        return Result.success("查询成功", page);
    }

//    根据ID获取影院详情
    @GetMapping("/{id}")
    public Result get(@PathVariable Long id) {
        return Result.success(cinemaMapper.selectCinemaById(id));
    }

//    新增影院
    @PostMapping
    public Result create(@RequestBody Cinema cinema) {
        int rows = cinemaMapper.insertCinema(cinema);
        return rows > 0 ? Result.success("新增成功") : Result.error(Constants.CODE_600, "新增失败");
    }

//    更新影院信息
    @PutMapping
    public Result update(@RequestBody Cinema cinema) {
        // 若传入 hallList 发生变化，需要删除被移除影厅下的座位
        if (cinema.getId() == null) {
            return Result.error(Constants.CODE_600, "缺少影院ID");
        }
        Cinema old = cinemaService.getById(cinema.getId());
        java.util.List<String> oldHalls = parseHallList(old != null ? old.getHallList() : null);
        java.util.List<String> newHalls = parseHallList(cinema.getHallList());
        int rows = cinemaMapper.updateCinemaById(cinema);
        if (rows <= 0) {
            return Result.error(Constants.CODE_600, "更新失败");
        }
        // 计算被移除的影厅集合并删除其座位
        java.util.Set<String> removed = new java.util.HashSet<>(oldHalls);
        removed.removeAll(new java.util.HashSet<>(newHalls));
        if (!removed.isEmpty()) {
            LambdaQueryWrapper<Seat> w = new LambdaQueryWrapper<>();
            w.eq(Seat::getCinemaId, cinema.getId()).in(Seat::getHallName, removed);
            // 忽略删除失败异常，主流程已成功更新影院
            try { seatService.remove(w); } catch (Exception ignored) {}
        }
        return Result.success("更新成功");
    }

//    删除影院
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        // 删除影院前，先清理该影院下所有座位
        try {
            LambdaQueryWrapper<Seat> w = new LambdaQueryWrapper<>();
            w.eq(Seat::getCinemaId, id);
            seatService.remove(w);
        } catch (Exception ignored) {}
        int rows = cinemaMapper.deleteCinemaById(id);
        return rows > 0 ? Result.success("删除成功") : Result.error(Constants.CODE_600, "删除失败");
    }

//    批量删除影院
    @DeleteMapping("/batch")
    public Result deleteBatch(@RequestBody java.util.List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error(Constants.CODE_600, "ID列表为空");
        }
        // 先清理这些影院的座位
        try {
            LambdaQueryWrapper<Seat> w = new LambdaQueryWrapper<>();
            w.in(Seat::getCinemaId, ids);
            seatService.remove(w);
        } catch (Exception ignored) {}
        int rows = cinemaMapper.deleteCinemasByIds(ids);
        return rows > 0 ? Result.success("批量删除成功") : Result.error(Constants.CODE_600, "批量删除失败");
    }

    /**
     * 解析 hallList(JSON 字符串) 为列表，兼容 null/"null"/空白/非法
     * @param hallRaw 原始 hall_list 字符串
     * @return 影厅名称列表（非 null）
     */
    private java.util.List<String> parseHallList(String hallRaw) {
        java.util.List<String> halls = new ArrayList<>();
        try {
            if (hallRaw != null && !hallRaw.trim().isEmpty() && !"null".equalsIgnoreCase(hallRaw.trim())) {
                ObjectMapper mapper = new ObjectMapper();
                halls = mapper.readValue(hallRaw, new TypeReference<java.util.List<String>>(){});
            }
        } catch (Exception ignored) {}
        return halls;
    }

}